﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ecdl.demo.model.expression;
using System.Xml.Serialization;
using ecdl.demo.persistence;
using ecdl.demo.model.precondition;

namespace ecdl.demo.model.file {
    public class FileTask : ITask {

        private readonly IVolumeProvider pathProvider;
        private readonly ITaskPresenter taskPresenter;

        public FileTask(ITaskPresenter taskPresenter, IVolumeProvider pathProvider) {
            Preconditions = new List<Precondition>();
            this.taskPresenter = taskPresenter;
            this.pathProvider = pathProvider;
        }

        private string text;

        [XmlAttribute("text")]
        public string Text {
            get { return text; }
            set {
                string path = pathProvider.GetPath();
                text = value.Replace("{PATH}", path);
            }
        }

        public List<Precondition> Preconditions { get; set; }
        public Expression Expression { get; set; }

        public ITaskEvaluation Evaluate() {
            ExpressionState state = Expression.Evaluate();

            ITaskEvaluation taskEvaluation;
            if (state.IsOk) {
                taskEvaluation = new TaskEvaluation(this, MaxPoints);
            } else {
                taskEvaluation = new TaskEvaluation(this, 0);
            }
            taskEvaluation.Cause = state.GetCause(true);
            return taskEvaluation;
        }

        [XmlAttribute("maxPoints")]
        public int MaxPoints { get; set; }

        public bool CanSubmit {
            get { return true; }
        }

        public void Activate() {
            taskPresenter.HidePresenter();
        }

        public void InitializePreconditions() {
            string path = pathProvider.GetPath();
            foreach (var preCondition in Preconditions) {
                preCondition.Execute(path);
            }
        }
    }

    public class FileTaskDTO : TaskDTO {

        public FileTaskDTO() {
            Preconditions = new List<Precondition>();
        }

        public List<Precondition> Preconditions { get; set; }

        public ExpressionDTO Expression { get; set; }


        public override ITask ToModel(ModelFactory factory) {
            FileTask task = factory.CreateModel<FileTask>();
            task.Text = Text;
            task.MaxPoints = MaxPoints;
            task.Preconditions = Preconditions;
            task.Expression = Expression.ToModel(factory);
            return task;
        }
    }
}
